//
//  PhotoViewController.m
//  RONGAO
//
//  Created by maple on 2017/3/1.
//  Copyright © 2017年 wei wang. All rights reserved.
//

#import "PhotoViewController.h"
#import "PhotoCollectionViewCell.h"
#import "PhotoCollectionReusableView.h"
#import "LookPhotoViewController.h"
#import "LocaViewController.h"
#import "photomodel.h"
#import "DeletView.h"
#define DOCSFOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/"]
#define VideoPath [DOCSFOLDER stringByAppendingPathComponent:@"test.mp4"]


@interface PhotoViewController ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    BOOL isEditor; //编辑模式
}
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)UICollectionViewFlowLayout *collectionLayout;

/**
 存储所有图片的状态
 */
@property (nonatomic,strong)NSMutableArray *selectArray;
/** <#Description#> **/
@property(nonatomic,strong) NSMutableArray *titleArray;
@property (nonatomic,strong)NSArray *dataSource;

/** camera **/
@property(nonatomic,strong) Camera *camera;

/** deleview **/
@property(nonatomic,strong) DeletView *deletView;


/** deletselctImageInfo **/
@property(nonatomic,strong) NSMutableArray *deletselctImageArray;
@end


float const collectionViewSpace = 5;




@implementation PhotoViewController


- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    _titleArray = [NSMutableArray array];

    [self loadDataimage];
}
#pragma mark - viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigationStyle];
    [self masLayoutSubview];
    
    self.camera = [AppDelegate globalDelegate].cameraModel;
    
  
    __weak typeof(self) weakself = self;
    self.deletView.deletEvent = ^(){
        
        [weakself deletePhotos];
        
    };

}

- (void)loadDataimage{
    
    NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
    FMResultSet *rs = [[AppDelegate globalDelegate].database executeQuery:@"SELECT * FROM snapshot WHERE dev_uid=?", self.camera.uid];
    
    while([rs next]) {
        
        NSString *filePath = [rs stringForColumn:@"file_path"];
        NSLog(@"DB-snapshot-file_path:%@", filePath);
        [mutableArray addObject:[NSString stringWithFormat:@"%@", filePath]];
    }
    [rs close];
    
    NSArray *result = [mutableArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
        NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
        
        return [obj2 compare:obj1]; //降序
        
    }];
 
    [self category:result];
    

}
-(void)category:(NSArray *)dataArray
{
    
    if (!(dataArray.count>0)) {
        
        [self.collectionView reloadData];
        return;
    }
    //分好组的数组
    _titleArray=[NSMutableArray array];
    //遍历时，时间相同的装在同一个数组中，先取_dataArray[0]分一组
    NSMutableArray *currentArr=[NSMutableArray array];
    photomodel *info = [[photomodel alloc] init];
    info.timeStr =dataArray[0];
    info.select = NO;
    [currentArr addObject:info];
    [_titleArray addObject:currentArr];
    
    if(dataArray.count>1)
    {
        
        for (int i=1;i<dataArray.count;i++)
        {
            //取上一组元素并获取上一组元素的比较日期
            NSMutableArray *preArr=[_titleArray objectAtIndex:_titleArray.count-1];
//            PHAsset *tem=[preArr objectAtIndex:0];
//            NSDate *pretime1=tem.creationDate;
            
            NSString *rootTime = dataArray[0];
            NSArray *rootList = [rootTime componentsSeparatedByString:@"."];
            NSDate *pretime1 = [NSDate dateWithTimeIntervalSince1970:[rootList[0] integerValue]];
            
            NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init] ;
            [outputFormatter setLocale:[NSLocale currentLocale]];
            [outputFormatter setDateFormat:@"yyyy-MM"];
            NSString *pretime = [outputFormatter stringFromDate:pretime1];
            
            NSString *premonth=[[[[pretime componentsSeparatedByString:@" "] firstObject] componentsSeparatedByString:@"-"] objectAtIndex:1];
          //  NSString *preday=[[[[pretime componentsSeparatedByString:@" "] firstObject] componentsSeparatedByString:@"-"] objectAtIndex:2];
          //  NSString *preStr=[premonth stringByAppendingString:preday];
            NSString *preStr=premonth;

            //取当前遍历的字典中的日期
            
            
            
//            PHAsset *currentDict=[dataArray objectAtIndex:i];
//            NSString *pretime2=currentDict.creationDate;
            
            NSString *rootTime1 = dataArray[i];
            NSArray *rootList1 = [rootTime1 componentsSeparatedByString:@"."];
            NSDate *pretime2 = [NSDate dateWithTimeIntervalSince1970:[rootList1[0] integerValue]];
            
            
            NSDateFormatter *outputFormatter1 = [[NSDateFormatter alloc] init] ;
            [outputFormatter1 setLocale:[NSLocale currentLocale]];
            [outputFormatter1 setDateFormat:@"yyyy-MM"];
            NSString *time = [outputFormatter stringFromDate:pretime2];
            
            
            NSString *month=[[[[time componentsSeparatedByString:@" "] firstObject] componentsSeparatedByString:@"-"] objectAtIndex:1];
//            NSString *day=[[[[time componentsSeparatedByString:@" "] firstObject] componentsSeparatedByString:@"-"] objectAtIndex:2];
            NSString *currentStr=month;

//            NSString *currentStr=[month stringByAppendingString:day];
            //如果遍历当前字典的日期和上一组元素中日期相同则把当前字典分类到上一组元素中
            if([currentStr isEqualToString:preStr])
            {
                photomodel *info = [[photomodel alloc] init];
                info.timeStr =rootTime1;
                info.select = NO;

                [currentArr addObject:info];
            }
            //如果当前字典的日期和上一组元素日期不同，则重新开新的一组，把这组放入到分类数组中
            else
            {
                currentArr=[NSMutableArray array];
                photomodel *info = [[photomodel alloc] init];
                info.timeStr =rootTime1;
                info.select = NO;

                [currentArr addObject:info];
                
                
                
                [_titleArray addObject:currentArr];
                
            }
            
            
        }
        [self.collectionView reloadData];
    }
    
}
/*
- (NSArray *)dataSource{
    
    if (!_dataSource) {
        
        
        if (PHOTO_LOCAL_SOURCE_TYPE == self.localSourceType) {
                        //分好组的数组
//            NSMutableArray *titleArray=[NSMutableArray array];
//            //遍历时，时间相同的装在同一个数组中，先取_dataArray[0]分一组
//            NSMutableArray *currentArr=[NSMutableArray array];
//            [currentArr addObject:result[0]];
//            [titleArray addObject:currentArr];
            
            
            

            
            [self category:_dataSource];

            [self.collectionView reloadData];
        } else if(VIDEO_LOCAL_SOURCE_TYPE == self.localSourceType) {
            
            NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
            FMResultSet *rs = [[AppDelegate globalDelegate].database executeQuery:@"SELECT * FROM record WHERE dev_uid=?", self.camera.uid];
            
            while([rs next]) {
                
                NSString *filePath = [rs stringForColumn:@"file_path"];
                NSLog(@"DB-record-file_path:%@", filePath);
                [mutableArray addObject:[NSString stringWithFormat:@"%@", filePath]];
                
            }
            [rs close];
            
            _dataSource = [[NSArray alloc] initWithArray:mutableArray];
            [self category:_dataSource];

            [self.collectionView reloadData];

        }

    }

    return _dataSource;
}
*/
#pragma mark - configUI
- (void)setNavigationStyle{
    [self setNavigationTitle:@"拍照相册" titleColor:[UIColor colorWithRed:210/255.0 green:177/255.0 blue:104/255.0 alpha:1]];
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
    [self setRightButtonTitle:@"编辑"];
}




#pragma mark - collectionView Deleagete &DataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return _titleArray.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSArray *ary=_titleArray[section];
    return ary.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    PhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"photoCell" forIndexPath:indexPath];
    NSArray *ary=_titleArray[indexPath.section];

    photomodel *info = ary[indexPath.row];
    
    NSString *albumDirectoryPath = self.directoryPath;
    NSLog(@"%@",[NSString stringWithFormat:@"%@",  info.timeStr]);

    cell.imageView.image = [UIImage imageWithContentsOfFile:[albumDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", info.timeStr]]];

    cell.selectImageView.hidden = !info.select;
    
    return cell;
    
}

- (BOOL)selectImageHidenWith:(NSString *)string
{
    if ([string isEqualToString:offSelect]) {
        return YES;
    }
    return NO;
}

//设置header的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(SCREEN_WIDTH, 40);
}


//每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat  with = (SCREEN_WIDTH - collectionViewSpace - 50)/4;
    
    return CGSizeMake(with,with);
}

//每一个分组的上左下右间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 20, 5, 20);
}

//设置header和footer的view
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    PhotoCollectionReusableView * view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"photoHead" forIndexPath:indexPath];
    
    if (kind == UICollectionElementKindSectionHeader) {
        
        NSArray *arr = _titleArray[indexPath.section];
        if (arr.count>0) {
            
            photomodel *info = _titleArray[indexPath.section][0];
            
            
            
                NSArray *rootList1 = [info.timeStr componentsSeparatedByString:@"."];
                NSDate *pretime2 = [NSDate dateWithTimeIntervalSince1970:[rootList1[0] integerValue]];
                
                NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init] ;
                [outputFormatter setLocale:[NSLocale currentLocale]];
                [outputFormatter setDateFormat:@"yyyy"];
                NSString *year = [outputFormatter stringFromDate:pretime2];
                NSDateFormatter *outputFormatter2 = [[NSDateFormatter alloc] init] ;
                [outputFormatter2 setLocale:[NSLocale currentLocale]];
                [outputFormatter2 setDateFormat:@"MM"];
                NSString *moth = [outputFormatter2 stringFromDate:pretime2];
        
                NSString *day = [NSString stringWithFormat:@"%ld",(long)[self howManyDaysInThisYear:[year intValue] withMonth:[moth intValue]]];
            
                view.timeLabel.text = [NSString stringWithFormat:@"%@-%@-01 - %@-%@",year,moth,moth,day];

            
            view.placeImage.hidden = NO;

        }else{
            
            view.timeLabel.text = @"";
            view.placeImage.hidden = YES;
        }
       
    }
    return view;
}

//点击
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row ;
    
    NSArray *arry = _titleArray[indexPath.section];
    NSString *imagefile = arry[indexPath.row];
    
    if (isEditor) { //编辑模式
        PhotoCollectionViewCell *cell =(PhotoCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
        
        photomodel *info = arry[indexPath.row];
        info.select = !info.select;
        if (cell.selectImageView.hidden == NO) {
            
            [self.deletselctImageArray removeObject:imagefile];

            
        }else{
            
            [self.deletselctImageArray addObject:imagefile];
            
        }
        [_collectionView reloadData];
    }else{
        
        if (PHOTO_LOCAL_SOURCE_TYPE == self.localSourceType){
            
            LookPhotoViewController *lookVC = [[LookPhotoViewController alloc]initWithNibName:@"LookPhotoViewController" bundle:nil];

            lookVC.directoryPath = self.directoryPath;
            lookVC.indexgroup = indexPath.section;
            self.hidesBottomBarWhenPushed = YES;
            
            [self.navigationController pushViewController:lookVC animated:YES];
        
        }else if (VIDEO_LOCAL_SOURCE_TYPE == self.localSourceType){
        
        }
       
    
    }
}

#pragma mark - 获取某年某月的天数
- (NSInteger)howManyDaysInThisYear:(NSInteger)year withMonth:(NSInteger)month{
    if((month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12))
        return 31 ;
    
    if((month == 4) || (month == 6) || (month == 9) || (month == 11))
        return 30;
    
    if((year % 4 == 1) || (year % 4 == 2) || (year % 4 == 3))
    {
        return 28;
    }
    
    if(year % 400 == 0)
        return 29;
    
    if(year % 100 == 0)
        return 28;
    
    return 29;
}

- (UICollectionView *)collectionView{
    
    if (!_collectionView) {
        __weak UIView *superView = self.view;
        _collectionLayout = [[UICollectionViewFlowLayout alloc]init];
        _collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:_collectionLayout];
        [superView addSubview:_collectionView];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor colorWithHexString:@"f8f7f7"];
        
        [_collectionView registerNib:[UINib nibWithNibName:@"PhotoCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"photoCell"];
        
        [_collectionView registerNib:[UINib nibWithNibName:@"PhotoCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"photoHead"];
        
        _collectionLayout.minimumLineSpacing = 2; //最小行距
        _collectionLayout.minimumInteritemSpacing = 1; //cell的最小间距

    }
    return _collectionView;
}

- (void)masLayoutSubview{
    
    __weak UIView *superView = self.view;
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(superView.mas_top);
        make.left.mas_equalTo(superView.mas_left);
        make.right.mas_equalTo(superView.mas_right);
        make.height.mas_equalTo(pxScaleHeight(1750));
        
    }];

    [self.deletView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.mas_equalTo(superView.mas_bottom);
        make.right.mas_equalTo(superView.mas_right);
        make.left.mas_equalTo(superView.mas_left);
        make.height.mas_equalTo(pxScaleHeight(170));
        
    }];

    
    
}

- (NSMutableArray *)deletselctImageArray{
    
    if (!_deletselctImageArray) {
     
        _deletselctImageArray = [NSMutableArray array];
    }
    return _deletselctImageArray;
}

- (DeletView *)deletView{
    
    if (!_deletView){
        
        _deletView = [[DeletView alloc] initWithFrame:self.view.bounds];
        _deletView.backgroundColor = [UIColor whiteColor];
        _deletView.hidden = YES;
        [self.view addSubview:_deletView];
    }
    
    return _deletView;
}

#pragma mark - 点击事件

/**
 右边按钮点击
 
 @param sender sender
 */
- (void)onRightButtonClick:(UIButton *)sender
{
    [self.deletselctImageArray removeAllObjects];

    if ([sender.currentTitle isEqualToString:@"编辑"]){ // 进入编辑模式
        
        isEditor = YES;
        [self  setLeftButtonImage:nil];
        [self setLeftButtonTitle:@"全选"];
        [self setRightButtonTitle:@"完成"];
        self.deletView.hidden = NO;
        return;
    }
    
        if ([sender.currentTitle isEqualToString:@"完成"]){ //退出编辑模式
        isEditor = NO;
        [self setNavigationStyle];
        self.deletView.hidden = YES;

            if (_titleArray.count>0) {
                
                
                for (int i = 0; i < _titleArray.count; i++) {
                    
                    
                    NSArray *array = _titleArray[i];
                    for (int j = 0; j < array.count; j++) {
                        photomodel *info = array[j];
                        info.select = NO;
                        NSString *str = array[j];
                        [self.deletselctImageArray addObject:str];
                    }
                    
                    
                }
                
            }
        [_collectionView reloadData];
        return;
    }
    
}

/**
 重写父类方法 左边按钮点击事件
 
 @param sender sender
 */
- (void)onLeftButtonClick:(UIButton *)sender
{
    if (isEditor) { //编辑模式
        //点击全选
        if ([sender.currentTitle isEqualToString:@"全选"]) {

            
            if (_titleArray.count>0) {
                
                
                for (int i = 0; i < _titleArray.count; i++) {
                    
                    
                    NSArray *array = _titleArray[i];
                    for (int j = 0; j < array.count; j++) {
                        photomodel *info = array[j];
                        info.select = YES;
                        NSString *str = array[j];
                        [self.deletselctImageArray addObject:str];
                    }
                    
                    
                }
                
            }

            
            [_collectionView reloadData];
            [self setLeftButtonTitle:@"取消"];
            
            return;
        }
        
        if ([sender.currentTitle isEqualToString:@"取消"]) {
            
            [self setLeftButtonTitle:@"全选"];
            
            if (_titleArray.count>0) {
                
                
                for (int i = 0; i < _titleArray.count; i++) {
                    
                    
                    NSArray *array = _titleArray[i];
                    for (int j = 0; j < array.count; j++) {
                        photomodel *info = array[j];
                        info.select = NO;
                        NSString *str = array[j];
                        [self.deletselctImageArray addObject:str];
                    }
                    
                    
                }
                
            }
            

            sender.titleLabel.text = @"全选";
            
            [self.deletselctImageArray removeAllObjects];
            
            [_collectionView reloadData];
            return;
        }

        
    }else{
        
        if ([self.navigationController.visibleViewController isMemberOfClass:[UITabBarController class]]) {
            return;
        }
        [self.navigationController popViewControllerAnimated:YES];
        
    }
}

/**
 重写父类方法 左边按钮
 
 @param title title
 */
- (void)setLeftButtonTitle:(NSString *)title{
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.leftButton];
    [self.leftButton setTitleColor:[UIColor colorWithHexString:@"#dab866"] forState:UIControlStateNormal];
    [self.leftButton.titleLabel setFont:[UIFont systemFontOfSize:14.0f]];
    [self.leftButton setTitle:title forState:UIControlStateNormal];
    [self.leftButton setFrame:CGRectMake(0, 0, BASE_TEXTSIZE(title, self.leftButton.titleLabel.font).width, BASE_TEXTSIZE(title,self.leftButton.titleLabel.font).height)];
}

- (void)deletePhotos {
    NSLog(@"+++func   deletePhotos");
    
    if (self.deletselctImageArray.count > 0) {
        
        
        for (photomodel *photoFile in self.deletselctImageArray) {
            
            NSLog(@"=====photoFile:%@",photoFile);
            [self deleteSnapshotRecords:photoFile.timeStr];
            
            //[self deletePhotoAtIndex:[index integerValue]];
        }

    }else{
        
        return [SVProgressHUD showInfoWithStatus:@"请选择需要删除的图片"];
    }
    
    
}

#pragma mark - --------------------------删除部分--------------------------

- (void)deleteSnapshotRecords:(NSString *)fileName {
    
    if ([AppDelegate globalDelegate].database != NULL) {
        
        FMResultSet *rs = [[AppDelegate globalDelegate].database executeQuery:@"SELECT * FROM snapshot WHERE file_path=?", fileName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        while([rs next]) {
            
            NSString *filePath = [rs stringForColumn:@"file_path"];
            [fileManager removeItemAtPath:[self pathForDocumentsResource: filePath] error:NULL];
            NSLog(@"camera(%@) snapshot removed", filePath);
        }
        
        [rs close];
        
        [[AppDelegate globalDelegate].database executeUpdate:@"DELETE FROM snapshot WHERE file_path=?", fileName];
        

    /*    for (int i; i < _titleArray.count; i++) {
            
            
            for (int j; j < [_titleArray[i] count]; j++) {
                
                photomodel *info = _titleArray[i][j];
                if ([info.timeStr isEqualToString:fileName]) {
                    
                    [_titleArray[i][j] removeObject:info];
                }
                
            }
        }
        */
        
        
     //   [_titleArray[i] removeObject:info];

        
        

        isEditor = NO;
        [self setNavigationStyle];
        self.deletView.hidden = YES;
      
        [self loadDataimage];
        

    }

    
}
- (NSString *) pathForDocumentsResource:(NSString *) relativePath {
    
    static NSString* documentsPath = nil;
    
    if (nil == documentsPath) {
        
        NSArray* dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        documentsPath = [dirs objectAtIndex:0];
    }
    
    return [documentsPath stringByAppendingPathComponent:relativePath];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
